# Figures 5 and 6

# 1. Makes the map of transitions between communities
# 2. Makes the map of GDP per capita in 2005

library(RColorBrewer)
library(cshapes)

#set the working directory here
setwd("")

# load the IGO membership array:
load("membership-expanded3.rda")

# load the communities data:
load("clubs of clubs data 2.rda")

# load the IGO statistics:
load("igostats5.rda")

source("ccode2cow.R")


### 1.  Calculate stability scores for each state over the whole period.
cowlist<-sort(unique(comm$cow))
stability<-rep(NA, length(cowlist))
names(stability)<-cowlist

for (i in 1:length(cowlist)){
	cow.current<-cowlist[i]
	x<-comm$comm.name[comm$cow==cow.current]
	transitions<-0
	for (n in 2:length(x)) if (x[n]!=x[n-1]) transitions<-transitions+1
	stability[i]<-transitions
	}
stability<-1-(stability/max(stability))

	
# Now produce a map of the stability:
m2005<-cshp(date=as.Date("2005-01-01"), useGW=FALSE)
m2005$cow<-ccode2cow(m2005$COWCODE)
m2005$stability<-stability[match(m2005$cow, names(stability))]
m2005$color<-rgb(m2005$stability, m2005$stability, 1)

png("Figure 5.png", width=480*4, height=480*2)
plot(m2005, col=m2005$color)
dev.off()


### 2.  Make a map showing GDP per capita:
comm2005<-subset(comm, year==2005)
comm2005$gdpcolor<-comm2005$gdppc/60000
comm2005$gdpcolor[is.na(comm2005$gdpcolor)]<-0
comm2005$gdpcolor[comm2005$gdpcolor>1]<-1
m2005$gdpcolor<-comm2005$gdpcolor[match(m2005$cow, comm2005$cow)]

png("Figure 6.png", width=480*4, height=480*2)
plot(m2005, col=rgb(1-m2005$gdpcolor, 1-m2005$gdpcolor, 1))
dev.off()